<?php

/*
 * File: mailControl.php
 * Description: Received Mail Example
 * Created: 03-06-2015
 * Author: Sara Zhou
 */


//$conn   = imap_open('{imap.163.com:993/imap/ssl}INBOX', 'lin1qun@163.com', 'jabin520');
//$some   = imap_search($conn, 'SUBJECT "HOWTO be Awesome" SINCE "8 August 2008"', SE_UID);
//$msgnos = imap_search($conn, 'UNSEEN');
//$uids =imap_search($conn, 'UNSEEN SINCE 20-Sep-2015');
//$status = imap_setflag_full($conn, 2, "\\SEEN");
////$status = imap_setflag_full($conn, imap_uid($conn,2), "\\SEEN",SE_UID);
////$status = imap_setflag_full($conn, imap_uid($conn,3), "\\SEEN",SE_UID);
////echo gettype($status) . "\n";
////echo $status . "\n";
//
//
//print_r($some);
//echo "2--->";
//print_r($msgnos);
//echo "3--->";
//print_r($uids);
////imap_close($conn);
//exit;


@header('Content-type: text/html;charset=UTF-8');
error_reporting(0);
ignore_user_abort(); // run script in background
set_time_limit(0); // run script forever
date_default_timezone_set('Asia/Shanghai');
include("receivemail.class.php");

class mailControl {

    //定义系统常量
    //用户名
    public $mailAccount = "lin1qun@163.com";
    public $mailPasswd = "jabin520";
    public $mailAddress = "lin1qun@163.com";
    public $mailServer = "imap.163.com";
    public $serverType = "imap";
    public $port = "993";
    public $now = 0;
    public $savePath = '';
    public $webPath = "../upload/";

    public function __construct() {
        $this->now = date("Y-m-d H:i:s", time());

        $this->setSavePath();
    }

    /**
     * mail Received()读取收件箱邮件
     *
     * @param
     * @access public
     * @return result
     */
    public function mailReceived() {

        // Creating a object of reciveMail Class
        $obj = new receiveMail($this->mailAccount, $this->mailPasswd, $this->mailAddress, $this->mailServer, $this->serverType, $this->port, false);

        //Connect to the Mail Box
        $res = $obj->connect();         //If connection fails give error message and exit
        if (!$res) {
            return array("msg" => "Error: Connecting to mail server");
        }
        //$serach=$obj->setSearchMails();
        // Get Total Number of Unread Email in mail box
        $tot = $obj->getTotalMails(); //Total Mails in Inbox Return integer value

        if ($tot < 1) { //如果信件数为0,显示信息
            return array("msg" => "No Message for " . $this->mailAccount);
        } else {
            $res = array("msg" => "Total Mails:: $tot<br>");

            for ($i = $tot; $i > 0; $i--) {
                $head = $obj->getHeaders($i);  // Get Header Info Return Array Of Headers **Array Keys are (subject,to,toOth,toNameOth,from,fromName)
                //处理邮件附件
                $files = $obj->GetAttach($i, $this->savePath); // 获取邮件附件，返回的邮件附件信息数组

                $imageList = array();
                foreach ($files as $k => $file) {
                    //type=1为附件,0为邮件内容图片
                    if ($file['type'] == 0) {
                        $imageList[$file['title']] = $file['pathname'];
                    }
                }
                $body = $obj->getBody($i, $this->webPath, $imageList);

                $res['mail'][] = array('head' => $head, 'body' => $body, "attachList" => $files);
                //$obj->deleteMails(1);			
//$obj->deleteMails($i); // Delete Mail from Mail box
//$obj->setFlagMails($i);
                //$obj->move_mails($i,"taskMail");
                //$obj->move_mails($i, "readyBox");
            }
            //$obj->deleteMails(2);
            $obj->close_mailbox();   //Close Mail Box
            return $res;
        }
    }

    public function getNoReadMail() {
        // Creating a object of reciveMail Class
        $obj = new receivemail($this->mailAccount, $this->mailPasswd, $this->mailAddress, $this->mailServer, $this->serverType, $this->port, false);

        //Connect to the Mail Box
        $res = $obj->connect();         //If connection fails give error message and exit
        if (!$res) {
            return array("msg" => "Error: Connecting to mail server");
        }
        $arr = $obj->getUnRead();
     
        if ($arr) {
            foreach ($arr as $i) {
         
                $head = $obj->getHeaders($i);  // Get Header Info Return Array Of Headers **Array Keys are (subject,to,toOth,toNameOth,from,fromName)
             
               //处理邮件附件
                $files = $obj->GetAttach($i, $this->savePath); // 获取邮件附件，返回的邮件附件信息数组

                $imageList = array();
                foreach ($files as $k => $file) {
                    //type=1为附件,0为邮件内容图片
                    if ($file['type'] == 0) {
                        $imageList[$file['title']] = $file['pathname'];
                    }
                }
                $body = $obj->getBody($i, $this->webPath, $imageList);
                $resb[] = array('head' => $head, 'body' => $body, "attachList" => $files);
                    }
              
            $obj->close_mailbox();   //Close Mail Box
        }
        
        return $resb;
    }

    /**
     * creatBox
     *
     * @access public
     * @return void
     */
    public function creatBox($boxName) {
        // Creating a object of reciveMail Class
        $obj = new receivemail($this->mailAccount, $this->mailPasswd, $this->mailAddress, $this->mailServer, $this->serverType, $this->port, false);
        $obj->creat_mailbox($boxName);
    }

    /**
     * Set save path.
     *
     * @access public
     * @return void
     */
    public function setSavePath() {
        $savePath = "../upload/" . date('Ym/', time());
        if (!file_exists($savePath)) {
            @mkdir($savePath, 0777, true);
            touch($savePath . 'index.html');
        }
        $this->savePath = dirname($savePath) . '/';
    }

    function _imap_utf8($text) {
        if (preg_match('/=?([a-zA-z0-9-]+)?(.*)?=/i', $text, $match)) {
            $text = imap_utf8($text);
            if (strtolower(substr($match[1], 0, 2)) == 'gb') {
                $text = iconv('gbk', 'utf-8', $text);
            }
            return $text;
        }
        return $this->_iconv_utf8($text);
    }

    function _iconv_utf8($text) {

        $s1 = iconv('gbk', 'utf-8', $text);
        $s0 = iconv('utf-8', 'gbk', $s1);
        if ($s0 == $text) {
            return $s1;
        } else {
            return $text;
        }
    }

}

$obj = new mailControl();
//创建邮箱
//收取邮件
$res = $obj->mailReceived();
print_r($res);
exit;
//$res = $obj->getNoReadMail();
//echo "<pre>";

foreach($res["mail"] as $k=>$v){
    
  
    $body=$obj->_iconv_utf8($v['body']);
    echo $body;
 
//$pp=explode("\r\n", $body);
//print_r($pp);

}
//foreach ($res['mail'] as $k=>$v){
//    echo  $obj->_imap_utf8($v['head']['subject'])."<br>";
//   echo $v[$k]['head']['subject'];
//}
?>
